<?php
class Helper_Url
{
	static $urlConfig = array(); //链接配置
	
	static $staticConfig = array(); //静态文件配置

	static $wyxParams = array();	//微游戏参数
	
	public static function initConfig()
	{
		if( empty( self::$urlConfig ) )
		{
			self::$urlConfig = & Common::getConfig( 'urlConfig' );
		}
			
		if( empty( self::$staticConfig ) )
		{
			self::$staticConfig = & Common::getConfig( 'static' );
		}

		if( empty( self::$wyxParams ) )
		{
			foreach( $_GET as $k => $v )
			{
				if( strpos( $k , WeiyouxiClient::PREFIX_PARAM ) === 0 )
				{
					self::$wyxParams[$k] = $v;
				}
			}
		}
	}
	
	/**
	 * 获取URL配置
	 *
	 * @param string $key
	 * @return sting
	 */
	public static function get( $key )
	{
	    self::initConfig();
	    return  isset( self::$urlConfig[ $key ] ) ? self::$urlConfig[ $key ] : self::$staticConfig[ $key ];
	}
	
	/**
	 * 生成地址
	 *
	 * @param string $con	//控制器
	 * @param string $method	//方法
	 * @param array $params //参数
	 */
	public static function homeUrl( $con = '' , $method = '' , $params = array() )
	{
		self::initConfig();
		return self::makeUrl( self::$urlConfig[ 'homeUrl' ] , $con , $method , $params );
	}
	
	/**
	 * 生成URL
	 *
	 * @param string $url //平台地址
	 * @param string $con	//控制器
	 * @param string $method	//方法
	 * @param array $params //参数
	 */
	public static function makeUrl( $url , $con , $method , $params = array() )
	{
		self::initConfig();
		$params = array_merge( $params , self::$wyxParams );
		$url .= $con;
		if( $method )
		    $url .= '/' . $method;
		    
		return $url . '?' . http_build_query( $params );
	}
	
	/**
	 * 微博CDN
	 * @param string $file //文件名
	 * @param string $type //类型
	 */
	public static function cdn( $file = '' , $type = 'image' )
	{
		self::initConfig();
		$staticType = self::$staticConfig[ 'staticType' ];
		
		//为了方便前端工程师调试压缩的js代码，使用这个参数可以切换为不使用压缩的js
		if( !empty( $_GET['wyx_debug_js_static_source'] ) )
		{
			$staticType = 'source';
		}
		
		$info = each( self::$staticConfig[ $staticType ][ $type ] );
		if( empty( $info['value'] ) )
		{
			reset( self::$staticConfig[ $staticType ][ $type ] );
			$info = each( self::$staticConfig[ $staticType ][ $type ] );
		}
		
		if( $file )
		{
			return $info['value'] . $file . "?v=" . self::$staticConfig['cdnVersion'];
		}
		else
		{
			return $info['value'];
		}
	}
        
          /**
         * 页面跳转
         * @param string $url 
         */
        public static function redirect( $url )
	{
		echo "<script type=\"text/javascript\">\nlocation.href = \"$url\";\n</script>";
	}
}